import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class FFListenGroup<T> {
  FFListen<T> listen;
  ValueNotifier<T> valueListenable; //ValueNotifier(0)

  FFListenGroup({
    required this.listen,
    required this.valueListenable,
  });

  ///翻译资源
  dispose(){
    if (listen.controller != null) {
      listen.controller?.dispose();
      listen.controller = null;
    }
  }

  ///开始执行动画
  start({
    required TickerProvider vsync, //with TickerProviderStateMixin
    required T begin,
    required T end,
    bool? repeat,
    Function(T value)? changeFun,
    Duration? duration,
    Function()? finishFun,
  }) {
    listen.controller = AnimationController(
        duration: duration ?? const Duration(milliseconds: 200), vsync: vsync);
    listen.animation = Tween<T>(begin: begin, end: end).animate(listen.controller!)
      ..addListener(
        () {
          valueListenable.value = listen.animation!.value;
          if (changeFun != null) {
            changeFun(listen.animation!.value);
          }

          if (listen.controller?.isCompleted == true) {
            if (listen.controller != null) {
              listen.controller?.dispose();
              listen.controller = null;
            }
            if (finishFun != null) {
              finishFun();
            }
          }
        },
      );

    if (repeat == true) {
      listen.controller?.repeat();
    } else {
      listen.controller?.forward(from: 0);
    }
  }

  ///监听动画
  ValueListenableBuilder uiListen2({
    required Widget Function(BuildContext ctx, T value, Widget? child) builder,
  }) {
    return ValueListenableBuilder<T>(valueListenable: valueListenable, builder: builder);
  }

  // ValueNotifier<double> valueListenable = ValueNotifier(0);
  static ValueListenableBuilder<T> uiListen<T>({
    required ValueListenable<T> valueListenable,
    required Widget Function(BuildContext ctx, T tValue, Widget? child) builder,
  }) {
    return ValueListenableBuilder<T>(valueListenable: valueListenable, builder: builder);
  }
}

class FFListen<T> {
  Animation? animation;
  AnimationController? controller;
}
